﻿using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace Ttifa.WebApiBase.Filters
{
    /// <summary>
    /// 过滤跨脚本攻击
    /// </summary>
    public class IllegalCharsHandler : DelegatingHandler
    {
        private const string ApiRegexScript = @"<\s*script\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)";

        /// <summary>
        /// 请求拦截处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (Regex.IsMatch(HttpUtility.HtmlDecode(request.RequestUri.AbsoluteUri), ApiRegexScript, RegexOptions.IgnoreCase))
            {
                return ApiResult.TaskResponse(ApiStatus.Illegal, "非法请求");
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}